<template>
  <div class="bg-[#1a2c38] w-full min-375 h-auto">
    <div
      class="container w-full mt-4 text-[#b1bac9]"
      v-if="activeObject && objKey"
    >
      <div
        class="bg-[#0f212e] px-4 py-2 inline-block mb-2 rounded-sm cursor-pointer"
        @click="router.go(-1)"
      >
        {{ $t("page.navbar.promotions") }} > {{ typeActive }}
      </div>
      <div class="" v-if="activeObject?.active_image_url?.length">
        <img
          class="rounded-lg shadow-[0 4px 6px -1px rgba(27, 23, 23, .2), 0 2px 4px -1px rgba(0, 0, 0, .12)]"
          :src="main.static_base_url + activeObject.active_image_url"
        />
      </div>
      <div
        class="notification-container mt-2 mb-2 flex gap-1 items-center"
        v-if="coupon_locked == 1"
      >
        <svg-icon class="text-[16px]" name="警告" />
        <span class="block mt-[1.5px]">{{
          $t("page.active.media_warning")
        }}</span>
      </div>
      <div
        class="text-xs mt-1"
        v-if="
          activeObject?.time &&
          activeObject?.time?.type &&
          activeObject.time.type == 'range'
        "
      >
        {{ $t("page.maneuver.ActivityTime") }}：
        {{
          dateTimeZone(
            activeObject.time.data.start_at,
            "{y}-{m}-{d}",
            main.timeZone
          )
        }}
        —
        {{
          dateTimeZone(
            activeObject.time.data.end_at,
            "{y}-{m}-{d}",
            main.timeZone
          )
        }}
      </div>

      <div
        v-if="objKey == 'bet_return_water'"
        class="bg-[#0f212e] mt-2 rounded-lg px-5 py-2 text-[14px] flex justify-between items-center"
      >
        <div>
          {{ $t("page.return_water.win_loss") }}： {{ activeObject?.amount }}
        </div>
        <div
          class="bg-[#409eff] text-white rounded px-4 py-2 cursor-pointer overflow-hidden whitespace-nowrap"
          @click="router.push('/')"
        >
          {{ $t("page.active.go_betting") }}
        </div>
      </div>

      <div
        v-if="main.isLogin && objKey == 'recharge_by_range'"
        class="bg-[#0f212e] mt-2 rounded-lg px-5 py-2 text-[14px] flex justify-between items-center"
      >
        <div>
          {{ $t("page.maneuver.accumulatedRecharge") }}：
          {{ activeObject?.amount }}
        </div>
        <div
          class="bg-[#409eff] text-white rounded px-4 py-2 cursor-pointer overflow-hidden whitespace-nowrap"
          @click="clickWallet"
        >
          {{ $t("page.maneuver.goRecharge") }}
        </div>
      </div>

      <div
        v-if="main.isLogin && objKey == 'spin_wheel'"
        class="bg-[#0f212e] mt-2 rounded-lg spin_wheel px-5 py-2 text-[14px] mb-4"
      >
        <div class="">{{ $t("page.lucky.my_lucky") }}:{{ luckyValue }}</div>
        <div class="text-[#1890ff] rounded px-4 py-2 cursor-pointer">
          <el-button
            type="primary"
            size="small"
            @click="router.push('/casino')"
            >{{ $t("page.active.go_betting") }}</el-button
          >
          <el-button
            class="mt-1"
            type="primary"
            size="small"
            @click="toggle"
            v-if="main.isLogin"
            >{{ $t("page.lucky.record") }}</el-button
          >
          <recordDialog :open="boolean" @close="toggle" />
        </div>
      </div>

      <div
        v-if="main.isLogin && objKey == 'redeem_code'"
        class="bg-[#0f212e] mt-2 rounded-lg px-5 py-2 text-[14px] items-center mb-4"
      >
        <div class="text-[#1890ff] rounded cursor-pointer">
          <ReInput
            v-model="code"
            :prefixName="$t('page.code.input_code')"
            @confirm="codeConfirm"
          />
        </div>
      </div>
      <!-- 新增活动 -->
      <div v-if="main.isLogin && objKey == 'media'">
        <div class="flex flex-col gap-1 mt-1">
          <div
            class="flex justify-between items-center gap-1"
            v-for="(item, index) in activeTabPath"
          >
            <div class="pr-[6px] flex items-center mt-2">
              <img
                :src="mediaImg[item.title]"
                class="w-[40px] h-[40px] mr-2"
                alt=""
              />
              <div>
                <p class="text-[18px] font-700">{{ item.title }}</p>
                <div
                  class="text-[14px] max-w-[200px] text-ellipsis whitespace-nowrap overflow-hidden"
                >
                  {{ item.link_url }}
                </div>
              </div>
            </div>
            <div>
              <button
                class="btn"
                color="#1475e1"
                size="default"
                @click="handleLick(item.link_url)"
              >
                {{ $t("page.active.visit") }}
              </button>
            </div>
          </div>
        </div>

        <el-dialog
          title=""
          v-model="dialogVisible"
          width="100%"
          @close="mediaCancel"
        >
          <div
            id="iframeId"
            class="iframe_src bg-[#0e1325] w-full h-full min-h-[400px] m-auto overflow-auto"
          ></div>
        </el-dialog>
      </div>
      <activeTable
        v-if="
          ['recharge_by_day', 'bet_return_water', 'recharge_by_range'].includes(
            objKey
          )
        "
        class="mt-3"
        :activeTabPath="activeTabPath"
        :columns="columns"
        :activeTab="'tab10'"
        :isMerge="true"
      ></activeTable>

      <activeTable
        v-if="['first_recharge'].includes(objKey)"
        class="mt-3"
        :activeTabPath="activeTabPathTab9"
        :columns="columns1"
        :activeTab="'tab10'"
        :isMerge="false"
      ></activeTable>

      <activeTable
        v-if="['first_recharge'].includes(objKey)"
        class="mt-3"
        :activeTabPath="activeTabPathTab91"
        :columns="columns2"
        :activeTab="'tab10'"
        :isMerge="false"
      ></activeTable>

      <div v-if="['spin_wheel'].includes(objKey)">
        <div class="flex w-full justify-center">
          <van-notice-bar
            class="w-2/4 van-notice-bar"
            :scrollable="true"
            :color="'#fff'"
            :background="'#0f212e'"
            :wrapable="false"
            left-icon="volume-o"
            :text="noticeList"
          />
        </div>
        <div class="w-full flex justify-center">
          <LuckyWheel
            ref="myLucky"
            width="320px"
            height="320px"
            :defaultConfig="defaultConfig"
            :prizes="prizes"
            :blocks="blocks"
            :buttons="buttons"
            @start="startCallback"
            @end="endCallback"
          />
        </div>
        <div class="flex items-center justify-between btnFlex">
          <el-button
            v-for="(item, index) in activeTabs"
            :key="index"
            :type="index + 1 == activeTypeShow ? 'primary' : 'default'"
            size="default"
            @click="activeTypeHandle(item)"
            >{{ item.name }}</el-button
          >
        </div>
      </div>

      <div class="mt-3" v-if="activeObject">
        <div v-html="activeObject.brief" class="img_auto"></div>
      </div>
    </div>

    <prizeResultDialog
      :open="prizeBol"
      @close="handleCLose"
      :data="prizeResultData"
    />
  </div>
</template>

<script setup name="Tools">
import { ref, onActivated, computed, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { mainAct } from "@/store/activeda.js";
import { dateTimeZone } from "@/utils/date";
import {
  getActiveCustomizeView,
  activeWheelRecord,
  activeExchange,
  activeBrief,
  activeWheel
} from "@/api/active";
import activeTable from "./components/activeTable.vue";
import recordDialog from "./components/recordDialog.vue";
import ReInput from "./components/reInput.vue";
import prizeResultDialog from "./components/prizeResultDialog.vue";
import { useI18n } from "vue-i18n";
import { mainWallet } from "@/store/wallet";
import { LuckyWheel } from "@lucky-canvas/vue";
import { useBoolean } from "@/hooks/useBoolean.js";
const walletDeitMony = mainWallet();
const { t } = useI18n();
const main = mainAct();
const route = useRoute();
const router = useRouter();
const activeTabPath = ref([]);
const columns = ref([]);
const luckyValue = ref(0);
const activeTypeShow = ref(1);
const { boolean, toggle } = useBoolean();
const { boolean: dialogVisible, toggle: dialogVisibleToggle } = useBoolean();
const { boolean: prizeBol, toggle: prizeToggle } = useBoolean();
const tab9Data = ref([]);
const coupon_locked = ref(0);
const dataTime = reactive({
  start_time: "",
  end_time: ""
});

import tg from "@/assets/active/tg.png";
import WhatsApp from "@/assets/active/WhatsApp.png";
import fb from "@/assets/active/fb.png";

const mediaImg = {
  Telegram: tg,
  WhatsApp: WhatsApp,
  Facebook: fb
};

// 动态创建 iframe
const createIframe = gameUrl => {
  console.log("gameUrl", gameUrl);

  // 确保在创建新的 iframe 之前，先清理旧的 iframe
  const container = document.getElementById("iframeId");
  // 动态创建 iframe
  const iframe = document.createElement("iframe");
  iframe.src = gameUrl; // 设置 URL
  iframe.frameBorder = 0; // 去掉边框
  iframe.className = "w-full h-full min-h-[400px]"; // 设置类名
  iframe.allow = "fullscreen"; // 添加允许权限，根据需要扩展
  iframe.sandbox =
    "allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation";
  iframe.onload = () => console.log("Iframe loaded successfully");
  iframe.onerror = () => console.error("Failed to load iframe.");
  container?.appendChild(iframe); // 添加到容器
  // sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation"
};

// 销毁 iframe
function clearIframe() {
  return new Promise((resolve, reject) => {
    const container = document.getElementById("iframeId");
    if (!container) {
      console.warn("Container for iframe not found.");
      resolve();
      return;
    }

    const iframe = container.querySelector("iframe");
    if (iframe) {
      try {
        // 设置 iframe 为空白页面，释放资源
        iframe.src = "about:blank"; // 或者 iframe.src = "javascript:void(0)";
      } catch (e) {
        iframe.src = "javascript:void(0)";
        console.error("Error setting iframe to blank:", e);
      }

      // 由于跨域问题，直接访问 iframe 内部内容会失败，因此不再清理内部文档
      // 但我们通过清空 src 和移除 iframe 元素，确保资源被释放

      try {
        // 清空 iframe 所占的 DOM 容器
        container.innerHTML = "";
        console.log("Iframe and its resources cleared.");
        resolve();
      } catch (e) {
        console.error("Error clearing iframe container:", e);
        reject(e);
      }
    } else {
      // 如果没有找到 iframe，则直接 resolve
      resolve();
    }
  });
}

const handleLick = url => {
  // main.isLogin ? window.open(url) : main.showLoginLayer();
  if (main.isApp) {
    dialogVisibleToggle();
    setTimeout(() => {
      createIframe(url);
    }, 200);
  } else {
    window.open(url);
  }
};

const mediaCancel = () => {
  clearIframe();
  dialogVisibleToggle();
};

const handleCLose = () => {
  if (prizeResultData.value && prizeResultData.value.type == "again") {
    startCallback();
  }
  prizeToggle();
};

const getDetailsData = () => {
  clickActiveTab();
  activeBrief({
    key: objKey.value
  }).then(res => {
    if (res?.errno == 0) {
      activeObject.value = res?.data.detail;
      let ruleData = res.data.detail.rule;
      coupon_locked.value = res.data.coupon_locked;
      //   投注返水
      if (["bet_return_water"].includes(objKey.value)) {
        activeTabPath.value = [];
        ruleData?.forEach(item => {
          const res = item.data.map(dataEntry => {
            return {
              name: item.level,
              reward_condition: dataEntry.reward_condition,
              value: `${t("page.return_water.proportion")}${
                dataEntry.value
              }%,${t("page.return_water.max_reward")}${dataEntry.max_value}${t(
                "layer.register.gold"
              )}`
            };
          });

          activeTabPath.value.push(res[0]);
        });
      }
      if (["recharge_by_range", "recharge_by_day"].includes(objKey.value)) {
        activeTabPath.value = [];
        ruleData.forEach(item => {
          item.data.forEach(dataEntry => {
            const length = item.level.length;
            activeTabPath.value.push({
              name: item.level,
              length: length, // 注意这里修正了属性名为 length
              dataLength: item.data.length, // 注意这里修正了属性名为 length
              reward_condition: dataEntry.reward_condition,
              value: dataEntry.value
            });
          });
        });
      }

      if (objKey.value == "first_recharge") {
        activeTabPath.value = [];
        activeTabPathTab9.value = [];
        activeTabPathTab91.value = [];
        if (ruleData && ruleData.length) {
          ruleData.forEach(item => {
            // 把item.reward_list的数组添加到activeTabPath中
            const res = item.reward_list.map(dataEntry => {
              return {
                reward_condition: `${dataEntry.data.reward_condition_min}-${dataEntry.data.reward_condition_max}`,
                value:
                  dataEntry.type === "rate"
                    ? `${dataEntry.data.value}%`
                    : dataEntry.data.value
              };
            });
            activeTabPath.value.push(res);
          });

          activeTabPathTab9.value = activeTabPath.value[0];
          activeTabPathTab91.value = activeTabPath.value[1];
        }
      }

      // 转盘
      if (objKey.value == "spin_wheel") {
        if (res.data?.detail?.time?.data) {
          dataTime.start_time = dateTimeZone(
            res.data.detail.time.data.start_at,
            "{y}-{m}-{d}",
            main.timeZone
          );
          dataTime.end_time = dateTimeZone(
            res.data.detail.time.data.end_at,
            "{y}-{m}-{d}",
            main.timeZone
          );
        } else {
          if (res.data?.detail?.start_time) {
            dataTime.start_time = dateTimeZone(
              res.data.detail.start_time,
              "{y}-{m}-{d}",
              main.timeZone
            );
            dataTime.end_time = dateTimeZone(
              res.data.detail.end_time,
              "{y}-{m}-{d} {h}:{i}:{s}",
              main.timeZone
            );
          } else {
            dataTime.start_time = "";
            dataTime.end_time = "";
          }
        }

        tab9Data.value = ruleData;
        // 更新奖品
        luckyValue.value = res.data.detail.lucky_value;
        updatePrizes(activeTypeShow.value - 1);
        loadNoticeList();
      }

      // 媒体社交活动
      if (objKey.value == "media") {
        activeTabPath.value = [];
        activeTabPath.value = ruleData;
      }
    }
  });
};

const columns1 = ref([
  {
    prop: "reward_condition",
    label: "page.first_recharge.money",
    align: "center",
    width: 80
  },
  {
    prop: "value",
    label: "page.first_recharge.amount",
    align: "center",
    width: 80
  }
]);
const columns2 = ref([
  {
    prop: "reward_condition",
    label: "page.second_recharge.money",
    align: "center",
    width: 80
  },
  {
    prop: "value",
    label: "page.first_recharge.amount",
    align: "center",
    width: 80
  }
]);

const clickActiveTab = () => {
  let arr = [];
  columns.value = [];
  switch (objKey.value) {
    case "recharge_by_day":
      arr = [
        {
          prop: "name",
          label: "page.vip.level",
          align: "center",
          width: 80,
          type: "img"
        },
        {
          prop: "reward_condition",
          label: "page.vip.evenyCumulativeAmount",
          align: "center",
          width: 80
        },
        {
          prop: "value",
          label: "page.vip.bonusGold",
          align: "center",
          width: 80
        }
      ];
      break;
    case "recharge_by_range":
      arr = [
        {
          prop: "name",
          label: "page.vip.level",
          align: "center",
          width: 80,
          type: "img"
        },
        {
          prop: "reward_condition",
          label: "page.vip.cumulativeAmount",
          align: "center",
          width: 80
        },
        {
          prop: "value",
          label: "page.vip.bonusGold",
          align: "center",
          width: 80
        }
      ];
      break;
    case "bet_return_water":
      arr = [
        {
          prop: "name",
          label: "page.vip.level",
          align: "center",
          width: 80,
          type: "img"
        },
        {
          prop: "reward_condition",
          label: "page.return_water.gold",
          align: "center",
          width: 80
        },
        {
          prop: "value",
          label: "page.return_water.return",
          align: "center",
          width: 80
        }
      ];
      break;
    case "tab9":
      arr = [
        [
          {
            prop: "reward_condition",
            label: "page.first_recharge.money",
            align: "center",
            width: 80
          },
          {
            prop: "value",
            label: "page.first_recharge.amount",
            align: "center",
            width: 80
          }
        ],
        [
          {
            prop: "reward_condition",
            label: "page.second_recharge.money",
            align: "center",
            width: 80
          },
          {
            prop: "value",
            label: "page.first_recharge.amount",
            align: "center",
            width: 80
          }
        ]
      ];
      break;
  }
  columns.value = arr;
};

const objKey = ref("");
const typeActive = ref();
onActivated(() => {
  objKey.value = route.query.key;
  console.log("objKey.value", objKey.value);
  if (/^\d+$/.test(objKey.value)) {
    getActiveCustomizeViewData();
  } else {
    typeActive.value = t(objKey.value);
    getDetailsData();
  }

  activeObject.value = {};
});

const activeTabPathTab9 = ref([]);
const activeTabPathTab91 = ref([]);

const activeObject = ref({});
const getActiveCustomizeViewData = () => {
  getActiveCustomizeView().then(res => {
    if (res?.errno == 0) {
      if (res.data.list.length) {
        activeObject.value = res.data.list.find(
          item => item.key == objKey.value
        );
      }

      typeActive.value = activeObject.value.title;
      activeObject.value.active_image_url = activeObject.value.active_image;
    }
  });
};

const code = ref("");
const codeConfirm = () => {
  if (!code.value.length)
    return ElMessage({
      type: "error",
      showClose: true,
      message: `${t("page.code.input_code")}`
    });
  if (!main.isLogin) {
    main.showLoginLayer();
    return;
  }
  const params = {
    redeem_code: code.value
  };

  activeExchange(params).then(res => {
    if (res.errno == 0) {
      let str = `${t("page.convert.success")}${res.data.coins}${t(
        "layer.register.gold"
      )}`;
      ElNotification({
        type: "success",
        showClose: true,
        message: str
      });
    }
  });
};

const clickWallet = async () => {
  walletDeitMony.getBankInfo("showRecharge");
};

import { prezesMap, pointerMap, buttonsMap, blocksMap } from "./prizes.js";
const currentData = ref([]);
const myLucky = ref();
const typeTime = ref("");
const activeType = ref("");
const activeTabs = ref([
  {
    tab: "silver",
    name: t("page.wheel.silver"),
    value: 1
  },
  {
    tab: "prime",
    name: t("page.wheel.prime"),
    value: 2
  },
  {
    tab: "diamond",
    name: t("page.wheel.diamond"),
    value: 3
  }
]);

const activeTypeHandle = item => {
  activeType.value = item.tab;
  activeTypeShow.value = item.value;
  updatePrizes(item.value - 1);
};

const defaultConfig = computed(() => {
  return {
    offsetDegree: 100
  };
});
const updatePrizes = index => {
  rewardData.value = {};
  currentData.value = tab9Data.value[index].reward_list;
  const colors = ["#283130", "#b13020", "#3a7531", "#20519a", "#a92f97"];

  blocks.value = [
    {
      padding: index == 2 ? "50px" : "28px",
      imgs: [
        {
          src: blocksMap[index],
          width: "280px",
          height: "280px",
          top: index == 1 ? "21px" : "20px"
        }
      ]
    }
  ];

  buttons.value = [
    {
      radius: "30%",
      imgs: [
        {
          src: buttonsMap[index],
          width: "100px",
          height: "100px",
          top: "-50px"
        }
      ]
    },
    {
      imgs: [
        { src: pointerMap[index], width: "25px", height: "45px", top: "-150px" }
      ]
    }
  ];
  prizes.value = currentData.value.map((item, i) => {
    const fontsText = item.type == "again" ? "" : `x${item.data.value || 1}`;
    return {
      background: colors[i % 3],
      fonts: [
        {
          text: fontsText,
          fontColor: "#fff",
          top: index == 2 ? "5px" : fontTop,
          fontSize: fontSize
        }
      ],
      imgs: [
        {
          src: prezesMap[item.type],
          top: index == 2 ? "30px" : prizesTop,
          width: "30px",
          height: "30px"
        }
      ]
    };
  });
};

const noticeList = ref("");
const loadNoticeList = () => {
  const typeMap = {
    silver: t("page.wheel.silver"),
    prime: t("page.wheel.prime"),
    diamond: t("page.wheel.diamond")
  };

  const lang = localStorage.getItem("lang");

  activeWheelRecord({ is_my: 0, page: 1, page_size: 10 }).then(res => {
    res.data.list
      .filter(item => item.prizes_type !== "none")
      .forEach(item => {
        const text =
          lang == "en"
            ? `${item.user_name} in ${typeMap[item.title]} ${setPrizes(
                item.prizes_type,
                item.prizes
              )}`
            : `${item.user_name} 在 ${typeMap[item.title]} 中获得 ${setPrizes(
                item.prizes_type,
                item.prizes
              )}`;

        // 如果已经存在通知，拼接分号
        if (noticeList.value) {
          noticeList.value += "; ";
        }

        // 添加新的通知文本
        noticeList.value += text;

        // 确保最多 20 条通知
        const notices = noticeList.value.split(";").filter(Boolean); // 分割并去除空项
        if (notices.length > 20) {
          notices.shift(); // 移除最早的通知
        }
        // 更新 noticeList.value，拼接回去，最后一个不需要分号
        noticeList.value = notices.join("; ") + (notices.length ? ";" : "");
      });
  });
};

const setPrizes = (type, value) => {
  const obj = {
    luck: `${t("page.lucky.lucky_value").replace("*", value)}`,
    again: `${t("page.lucky.again")}`,
    coins: `${t("page.lucky.coins_value").replace("*", value)}`,
    none: `${t("page.lucky.none")}`
  };
  return obj[type];
};

const fontSize = "12px";
const prizesTop = "45px";
const fontTop = "15px";
import coinsImg from "@/assets/active/icon5.png";
import aginImg from "@/assets/active/icon2.png";
import luckImg from "@/assets/active/icon1.png";
const prizes = ref([
  {
    background: "#283130",
    fonts: [
      { text: "x100", fontColor: "#fff", top: fontTop, fontSize: fontSize }
    ],
    imgs: [{ src: coinsImg, top: prizesTop, width: "30px", height: "30px" }]
  },
  {
    background: "#b13020",
    fonts: [
      { text: "x100", fontColor: "#fff", top: fontTop, fontSize: fontSize }
    ],
    imgs: [{ src: coinsImg, top: prizesTop, width: "30px", height: "30px" }]
  },
  {
    background: "#3a7531",
    fonts: [
      { text: "x100", fontColor: "#fff", top: fontTop, fontSize: fontSize }
    ],
    imgs: [{ src: coinsImg, top: prizesTop, width: "30px", height: "30px" }]
  },
  {
    background: "#283130",
    fonts: [
      { text: "x100", fontColor: "#fff", top: fontTop, fontSize: fontSize }
    ],
    imgs: [{ src: coinsImg, top: prizesTop, width: "30px", height: "30px" }]
  },
  {
    background: "#b13020",
    fonts: [
      { text: "x100", fontColor: "#fff", top: fontTop, fontSize: fontSize }
    ],
    imgs: [{ src: coinsImg, top: prizesTop, width: "30px", height: "30px" }]
  },
  {
    background: "#3a7531",
    fonts: [
      { text: "x100", fontColor: "#fff", top: fontTop, fontSize: fontSize }
    ],
    imgs: [{ src: coinsImg, top: prizesTop, width: "30px", height: "30px" }]
  },
  {
    background: "#283130",
    fonts: [
      { text: "x100", fontColor: "#fff", top: fontTop, fontSize: fontSize }
    ],
    imgs: [{ src: coinsImg, top: prizesTop, width: "30px", height: "30px" }]
  },
  {
    background: "#b13020",
    fonts: [
      { text: "x100", fontColor: "#fff", top: fontTop, fontSize: fontSize }
    ],
    imgs: [{ src: coinsImg, top: prizesTop, width: "30px", height: "30px" }]
  },
  {
    background: "#3a7531",
    fonts: [
      { text: "x100", fontColor: "#fff", top: fontTop, fontSize: fontSize }
    ],
    imgs: [{ src: coinsImg, top: prizesTop, width: "30px", height: "30px" }]
  }
]);
import hj4 from "@/assets/active/by2.png";
import jp3 from "@/assets/active/jg3.png";
const blocks = ref([
  {
    padding: "28px",
    // background: "#869cfa",
    imgs: [{ src: hj4, width: "280px", height: "280px", top: "20px" }]
  }
]);

import jg4 from "@/assets/active/jg4.png";
const buttons = ref([
  {
    background: "#ff9a9a",
    radius: "30%",
    imgs: [{ src: jp3, width: "100px", height: "100px", top: "-50px" }]
  },
  {
    imgs: [{ src: jg4, width: "25px", height: "45px", top: "-150px" }]
  }
]);
const rewardData = ref({});
const prizeResultData = ref();
let shouldTogglePrize = false; // 初始化状态变量
const startCallback = () => {
  // 没有登录 或者 时间超时
  // 超时

  if (!main.isLogin) {
    if (main2._isMobile) {
      router.push("/login");
    } else {
      main.showLoginLayer("no");
    }
    return;
  }

  if (new Date(dataTime.end_time).getTime() < new Date().getTime()) {
    ElMessage.warning(`${t("page.wheel.tipMsg")}`);
    return;
  }

  // 如果上一次是再来一次 不需要校验幸运值是否足够 因为再来一次不需要
  if (prizeResultData.value) {
    // 不是再来一次 判断够不够 不够不执行
    if (prizeResultData.value.type !== "again") {
      if (
        luckyValue.value < tab9Data.value[activeTypeShow.value - 1]?.luck_value
      ) {
        ElMessage.warning(`${t("page.wheel.tips")}`);
        return;
      }
    }
  }
  // 第一次进来
  else {
    if (
      luckyValue.value < tab9Data.value[activeTypeShow.value - 1]?.luck_value
    ) {
      ElMessage.warning(`${t("page.wheel.tips")}`);
      return;
    }
  }

  if (!main.isLogin) {
    main.showLoginLayer();
    return;
  }

  const reward_list = currentData.value;
  const active_type = activeTabs.value[activeTypeShow.value - 1].tab;
  const params = {
    active_type: active_type,
    brief: rewardData.value?.brief || ""
  };
  myLucky.value.play();

  activeWheel(params)
    .then(res => {
      // 设置状态变量
      shouldTogglePrize = res.errno === 0;
      console.log("activeWheel----res", res, res.errno, reward_list);
      if (res.errno == 0) {
        const index = reward_list.findIndex(item => item.key == res.data.key);
        prizeResultData.value = reward_list[index];
        rewardData.value = res.data;
        myLucky.value.stop(index);
        luckyValue.value = res.data.lucky;
        loadNoticeList();
      } else {
        setTimeout(() => {
          // 报错时，找到没有奖励的索引
          const index = reward_list.findIndex(item => item.type == "none");

          // 调用stop停止旋转并传递中奖索引
          myLucky.value.stop(index);
        }, 3000);
      }
    })
    .catch(err => {
      // 错误时更新状态变量
      shouldTogglePrize = false;
      setTimeout(() => {
        // 报错时，找到没有奖励的索引
        const index = reward_list.findIndex(item => item.type == "none");
        // 调用stop停止旋转并传递中奖索引
        myLucky.value.stop(index);
      }, 3000);
    });
};

const endCallback = prizes => {
  console.log("end", prizes);
  // 根据状态变量决定是否调用 prizeToggle
  if (shouldTogglePrize) {
    prizeToggle();
    // 重置状态变量
    shouldTogglePrize = false;
  } else {
    console.warn("No toggle action performed due to invalid state.");
  }
};
</script>
<style scoped lang="less">
.bgc {
  border-radius: 12px 12px 0 0;
  background: url("../../assets/imgs/header_bgc.png");
  background-size: 100% 100%; /* 覆盖整个元素区域 */
  background-repeat: no-repeat; /* 不重复图片 */
  background-position: center; /* 居中显示 */
}

.imgpic {
  transition: 0.3s;
}
.imgpic:hover {
  transform: translateY(-4%);
}

.img_auto {
  :deep(img) {
    width: auto;
    height: 100%;
  }
}

@media (max-width: 600px) {
  .spin_wheel {
    display: flex;
    align-items: center;
    flex-direction: column;
  }
}
.spin_wheel {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

:deep(.el-dialog) {
  background: #1a2c38;
}

// 警告条样式
.notification-container {
  display: flex;
  align-items: center;
  border: 1px dashed orange;
  padding: 10px;
  color: #fa8c16;
  font-size: 13px;
  border-radius: 4px;
  vertical-align: middle;

  span {
    line-height: 16px;
  }
}

.notification-container i {
  margin-right: 8px;
  font-size: 16px;
  color: #faad14; /* 图标颜色 */
}

.btn {
  width: 80px;
  height: 34px;
  display: flex;
  justify-content: center;
  font-size: 14px;
  align-items: center;
  border: 1px solid #1475e1;
  color: #fff;
  border-radius: 4px;
}
</style>
